package com.neuedu.javase.net;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @auth 金山老师
 * title:   书籍代码
 * creatime: 2022-10-06 10:46
 * 描述 : 客户端
 */
public class Client {

    public Client(String serverIP,int port) throws IOException, InterruptedException {

        //
        Socket socket = new Socket(serverIP ,port);

        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));



        Scanner scn = new Scanner(System.in);

        while( true){

            //从控制台读取字符串
            String input = scn.nextLine();
            //发送给服务端
            os.write((input+"\r\n").getBytes());
            os.flush();
            //在段护短断开的连接
            if("exit".equals(input)){
                break;
            }

            //等着服务端发送
            while (!br.ready()){
                Thread.sleep(500);
            }

            String line = br.readLine();
            System.out.println("服务器发送过来的:"+line);
            if("exit".equals(line)){
                System.out.println("byebye");
                os.write("say bye".getBytes());

                break;
            }
        }

        is.close();
        os.close();
        socket.close();

    }

    public static void main(String[] args) throws IOException, InterruptedException {
//        String ip = "192.168.10.1";
//        String ip = "127.0.0.1";
        String ip = "localhost";
        int port = 9999;
        new Client(ip,port);
    }

}
